## setup ##

# clean environment
rm(list=ls())

# load packages
library(sandwich)
library(lmtest)
library(ggplot2)
library(tidyverse)


# load data
 dat <- read.csv2("data_experiment_outcomes_csv.csv",
                  encoding = 'UTF-8')

## assign correct types (just to be safe)
# outcome variable to numeric
dat$response <- as.numeric(as.character(dat$response))

# IVs to numeric
dat$immback <- as.numeric(as.character(dat$immback))
dat$partisan <- as.numeric(as.character(dat$partisan))


## estimate models ##

# models with main treatment effects 
overall_nocov <- lm(response ~ immback + partisan, data=dat)
overall_nocov_rob <- coeftest(overall_nocov, vcov = vcovHC(overall_nocov, "HC1"))
overall_nocov_rob <- overall_nocov_rob[2:3,1:2]

# by ideological camp
right_nocov <- lm(response ~ immback + partisan, data=dat[dat$left==0,])
right_nocov_rob <- coeftest(right_nocov, vcov = vcovHC(right_nocov, "HC1"))
right_nocov_rob <- right_nocov_rob[2,1:2]

left_nocov <- lm(response ~ immback + partisan, data=dat[dat$left==1,])
left_nocov_rob <- coeftest(left_nocov, vcov = vcovHC(left_nocov, "HC1"))
left_nocov_rob <- left_nocov_rob[2,1:2]

# model with interaction between treatments 
int_overall_nocov <- lm(response ~ immback*partisan, data=dat)
int_overall_nocov_rob <- coeftest(int_overall_nocov, vcov = vcovHC(int_overall_nocov, "HC1"))
int_overall_nocov_rob <- int_overall_nocov_rob[4,1:2]


# combine models
ests <- rbind(overall_nocov_rob, 
              right_nocov_rob,
              left_nocov_rob,
              int_overall_nocov_rob)


## create data frame with estimates ##

ests <- data.frame(ests)

names(ests) <- c("coef", "se")

ests$treat <- c("Immigrant Background", "Partisan", "Immigrant Background", "Immigrant Background", "Immigrant Background*\nPartisan")
ests$treat <- factor(ests$treat, levels=c("Immigrant Background", "Partisan", "Immigrant Background*\nPartisan"))

ests$sample <- c("Overall", "Overall", "Rightist\nParty", "Leftist\nParty", "Overall")
ests$sample <- factor(ests$sample, levels=c("Overall", "Rightist\nParty", "Leftist\nParty"))


## create plot ##

ggplot(data=ests, aes(x=sample, y=coef)) +
  geom_hline(yintercept=0, linetype="dashed") +
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se), size=.4, width=.2, position = position_dodge(width = 0.3)) +
  geom_point(position = position_dodge(width = 0.3), size=2) +
  facet_wrap(~treat, scales="free_x") +
  theme_bw() +
  theme(panel.grid = element_blank(), legend.position = "bottom", text = element_text(size=14)) +
  scale_y_continuous(breaks=seq(-.2, .3, .05)) +
  ylab("Treatment Effect") + xlab("Sample")

